<template>
  <div class="account-settings">
    <el-tabs v-model="activeTab">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="basic">
        <el-form
          ref="basicFormRef"
          :model="basicForm"
          :rules="basicRules"
          label-width="100px"
          class="settings-form"
        >
        
          <el-form-item label="头像" prop="avatar">
            <div class="avatar-uploader">
              <el-upload
                class="avatar-upload"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleAvatarChange"
              >
                <img v-if="avatarUrl" :src="avatarUrl" class="avatar-image" />
                <el-icon v-else class="avatar-uploader-icon"><plus /></el-icon>
              </el-upload>
              <div class="avatar-tips">点击上传头像，支持JPG、PNG格式，大小不超过2MB</div>
            </div>
          </el-form-item>
          
          <el-form-item label="用户名" prop="username">
            <el-input v-model="basicForm.username" disabled />
          </el-form-item>
          
         
          
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="basicForm.phone" maxlength="11">
              <template #append>
                <el-button type="primary" @click="verifyPhone" :disabled="!canVerifyPhone">
                  {{ phoneVerifyText }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="basicForm.email">
              <template #append>
                <el-button type="primary" @click="verifyEmail" :disabled="!canVerifyEmail">
                  {{ emailVerifyText }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveBasicInfo">保存修改</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
      
    
    </el-tabs>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="500px"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            show-password
            placeholder="请输入当前密码"
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            show-password
            placeholder="请输入新密码"
          />
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            show-password
            placeholder="请再次输入新密码"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPasswordChange">
            确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getUserInfo, updateUserInfo, uploadAvatar } from '@/api/user'
import { Plus } from '@element-plus/icons-vue'
import request from '@/api/request'  // 导入request，用于获取baseURL
import { getFullAvatarURL } from '@/utils/common'

// 当前激活的标签页
const activeTab = ref('basic')

// 基本信息表单
const basicFormRef = ref(null)
const basicForm = reactive({
  id: '',
  username: '',
  nickname: '',
  phone: '',
  email: '',
  avatar: ''
})

// 头像URL
const avatarUrl = ref('')

// 头像文件
const avatarFile = ref(null)

// 处理头像选择
const handleAvatarChange = (file) => {
  // 检查文件类型和大小
  const isJPGOrPNG = file.raw.type === 'image/jpeg' || file.raw.type === 'image/png'
  const isLt2M = file.raw.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像只能是JPG或PNG格式')
    return
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过2MB')
    return
  }

  // 保存文件对象
  avatarFile.value = file.raw
  
  // 预览头像
  avatarUrl.value = URL.createObjectURL(file.raw)
  
  // 上传头像
  uploadAvatarFile()
}

// 基本信息验证规则
const basicRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 密码修改表单
const passwordFormRef = ref(null)
const passwordDialogVisible = ref(false)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 验证状态
const phoneVerified = ref(true)
const emailVerified = ref(true)

// 计算属性：是否可以验证手机号
const canVerifyPhone = computed(() => {
  return !phoneVerified.value && /^1[3-9]\d{9}$/.test(basicForm.phone)
})

// 计算属性：是否可以验证邮箱
const canVerifyEmail = computed(() => {
  return !emailVerified.value && /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(basicForm.email)
})

// 计算属性：手机验证按钮文本
const phoneVerifyText = computed(() => {
  return phoneVerified.value ? '已验证' : '去验证'
})

// 计算属性：邮箱验证按钮文本
const emailVerifyText = computed(() => {
  return emailVerified.value ? '已验证' : '去验证'
})

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const { data } = await getUserInfo()
    // 确保包含用户ID
    Object.assign(basicForm, {
      id: data.id,
      username: data.username,
      nickname: data.nickname,
      phone: data.phone,
      email: data.email,
      avatar: data.avatar
    })
    
    // 设置头像URL，处理为完整URL
    if (data.avatar) {
      avatarUrl.value = getFullAvatarURL(data.avatar);
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 保存基本信息
const saveBasicInfo = async () => {
  if (!basicFormRef.value) return
  
  try {
    await basicFormRef.value.validate()
    await updateUserInfo(basicForm)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败', error)
    ElMessage.error('保存失败，请稍后再试')
  }
}

// 修改密码
const changePassword = () => {
  passwordDialogVisible.value = true
}

// 提交密码修改
const submitPasswordChange = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    // 实际应用中应该调用API
    // await userApi.changePassword(passwordForm)
    
    ElMessage.success('密码修改成功')
    passwordDialogVisible.value = false
    
    // 清空表单
    passwordForm.oldPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 更换手机号
const changePhone = () => {
  // 实际应用中应该打开更换手机号的对话框
  ElMessage.info('更换手机号功能开发中')
}

// 更换邮箱
const changeEmail = () => {
  // 实际应用中应该打开更换邮箱的对话框
  ElMessage.info('更换邮箱功能开发中')
}

// 验证手机号
const verifyPhone = () => {
  // 实际应用中应该打开手机号验证的对话框
  ElMessage.info('手机号验证功能开发中')
}

// 验证邮箱
const verifyEmail = () => {
  // 实际应用中应该打开邮箱验证的对话框
  ElMessage.info('邮箱验证功能开发中')
}

// 手机号脱敏处理
const maskPhone = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

// 邮箱脱敏处理
const maskEmail = (email) => {
  if (!email) return ''
  const [username, domain] = email.split('@')
  const maskedUsername = username.length > 3 
    ? username.slice(0, 3) + '****' 
    : username.slice(0, 1) + '****'
  return `${maskedUsername}@${domain}`
}

// 头像上传文件
const uploadAvatarFile = async () => {
  if (!avatarFile.value) return
  
  try {
    const formData = new FormData()
    formData.append('file', avatarFile.value)
    
    const res = await uploadAvatar(formData)
    
    if (res.code === 200) {
      // 更新头像URL并显示
      basicForm.avatar = res.data.url
      avatarUrl.value = getFullAvatarURL(res.data.url);
      ElMessage.success('头像上传成功')
      
      // 更新头像显示到个人中心页面
      const userStr = localStorage.getItem('user')
      if (userStr) {
        const user = JSON.parse(userStr)
        user.avatar = res.data.url
        localStorage.setItem('user', JSON.stringify(user))
      }
    } else {
      ElMessage.error(res.message || '头像上传失败')
      // 上传失败时恢复原头像
      avatarUrl.value = getFullAvatarURL(basicForm.avatar);
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败，请稍后重试')
    // 上传失败时恢复原头像
    avatarUrl.value = getFullAvatarURL(basicForm.avatar);
  } finally {
    avatarFile.value = null
  }
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

.account-settings {
  .settings-form {
    max-width: 600px;
    margin: 0 auto;
    padding: var(--spacing-lg) 0;
    
    .avatar-uploader {
      text-align: center;
      margin-bottom: 20px;
      
      .avatar-upload {
        display: inline-block;
      }
      
      .avatar-image {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        object-fit: cover;
        border: 1px solid var(--border-color-light);
      }
      
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 100px;
        height: 100px;
        border: 1px dashed var(--border-color);
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        
        &:hover {
          border-color: var(--primary-color);
          color: var(--primary-color);
        }
      }
      
      .avatar-tips {
        font-size: 12px;
        color: #999;
        margin-top: 8px;
      }
    }
  }
  
  .security-list {
    max-width: 800px;
    margin: 0 auto;
    padding: var(--spacing-lg) 0;
    
    .security-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: var(--spacing-md) 0;
      border-bottom: 1px solid var(--border-color-light);
      
      &:last-child {
        border-bottom: none;
      }
      
      .item-info {
        .item-title {
          font-size: 1rem;
          font-weight: 500;
          color: var(--text-primary);
          margin-bottom: 4px;
        }
        
        .item-desc {
          font-size: 0.9rem;
          color: var(--text-secondary);
        }
      }
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .account-settings {
    .settings-form {
      padding: var(--spacing-md) 0;
    }
    
    .security-list {
      padding: var(--spacing-md) 0;
    }
  }
}
</style> 